import router from '@/router';
import req from '@/request';
import store from '@/store';
function redirectToLogin() {
    sessionStorage.removeItem('ticket');
    location.href = `http://192.168.3.83:3001?target=http://${location.host}`
}

async function getUserInfo () {
    const userInfo = await req.user.getUserDetailByTicket();
    if (!userInfo.success) {
        redirectToLogin();
    }
    store.commit('global/SET_USERINFO', userInfo.value);
}
class Permission {
    constructor() {
        this.beforeEach();
    }
    beforeEach ():void {
        router.beforeEach(async (to, from, next) => {
            if (sessionStorage.getItem('ticket')) {
                console.log(store);
                await getUserInfo()
                return next();
            }
            const param = location.href.split('?')[1];
            if (!param) redirectToLogin();
            const ticketP = param.split('&').find(item => item.includes('ticket'));
            const ticket = ticketP && ticketP.split('=')[1];
            if (ticket) {
                sessionStorage.setItem('ticket', ticket);
                await getUserInfo();
                return next();
            }
            redirectToLogin();
        })
    }
}

export default Permission;
